# -*- coding: utf-8 -*-
#这是个测试wsgi
import re, cgi, io, urllib,json
from cgi import parse
from common.debug import Debug
from flup.server.fcgi import WSGIServer  



def application(environ, start_response):
    '''
    apache wsgi模块，会调用这个函数，来处理每一个请求
    '''
    stringbb="result:"
    #从environ里面解析出http参数来
    mydebug=Debug()
  
    rquest_method =environ["REQUEST_METHOD"]  
    if rquest_method=='GET':
        params = parse(None, environ)
    else:  
        post_env = environ.copy() 
        post_env['QUERY_STRING'] = ''
                    
        #form = cgi.FieldStorage(fp=environ['wsgi.input'],environ=post_env,keep_blank_values=True)
        #i=0 
        #for key in form.keys():  
        #    i+=1
        #    stringbb +=key+str(i)+" : "+form[key].value+ " abc123 \r\n"    
    #return response(environ, start_response, stringbb)
        #return response(environ, start_response, data)
        form = cgi.FieldStorage(fp=post_env['wsgi.input'],environ=post_env,keep_blank_values=True)
        mydebug.d("test.wsgi wugang:%s" % repr(form))      
        paramsbb ='{"result": "ok"'
        for key in form.keys(): 
            paramsbb+=',"'+key+'": "'+form.getfirst(key)+'"'              
        paramsbb +='}'        
        #encodedjson =json.dumps(paramsbb, sort_keys=True) 
    return response(environ, start_response, paramsbb)
        #__getattr__(self,self.__attrs)
        #params =environ["wsgi.input"].read()
       
    
    #mymsg=get_environ(environ)
    #return response(environ, start_response,mymsg)   
    
    #假设http请求里面一定有两个键为name和age的参数
    #获取name,age参数的值：
 
    if len(params) > 0:
        if (params.get('name') != None) and (params.get('age') != None):
            nameparam = params['name']
            ageparam = params['age']
            return response(environ, start_response, 'name is %s,  age is %s' % (nameparam, ageparam))
        else:
            return response(environ, start_response, 'wugangisaboy')
    else:
        return response(environ, start_response, 'babywugangboy')


def response(environ, start_response, msg):
    '''
    对请求做一个文本格式的应答，msg可以是一个json文本
    '''
    status = '200 ok'
    output = msg        
    response_headers = [('Content-type', 'text/plain;charset=utf-8'),
            ('Content-Length', str(len(output)))]
    
    start_response(status, response_headers)
    
    return [output]  


def get_environ(environ):  
    rquest_method = environ["REQUEST_METHOD"]  
    str = "rquest_method:" + rquest_method + "\r\n"  
    query_string = environ["QUERY_STRING"]  
    str += ",query_string:" + query_string + "\r\n"  
    script_filename = environ["SCRIPT_FILENAME"]  
    str += ",script_filename:" + script_filename + "\r\n"  
    script_name = environ["SCRIPT_NAME"]  
    str += ",script_name:" + script_name + "\r\n"  
    rquest_uri = environ["REQUEST_URI"]  
    str += ", rquest_uri:" + rquest_uri + "\r\n"  
    remote_addr = environ["REMOTE_ADDR"]  
    str += ",remote_addr:" + remote_addr + "\r\n"  
    remote_port = environ["REMOTE_PORT"]  
    str += ",remote_port:" + remote_port + "\r\n"  
      
    data = environ["wsgi.input"].read()  
    str += ", data:" + data + "\r\n"  
    return str      

def __getattr__(self, attr):   
    if(attr == "params" and "params" not in self.__attrs):   
        fp = None  
        if(self.method == "POST"):   
            content = self.winput.read(int(self.env.get("CONTENT_LENGTH","0")))   
            fp = io.StringIO(urllib.parse.unquote(content.decode("ISO-8859-1"),encoding=self.encoding))   
        self.fs = cgi.FieldStorage(fp = fp, environ=self.env, keep_blank_values=1)# 创建FieldStorage   
        self.params = {}   
        for key in self.fs.keys():   
            self.params[key] = self.fs[key].value   
        self.__attrs["params"] = self.params   
    return self.__attrs[attr]   
